package com.chenyue.cm.common.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.common.dao.JdHotKeyWordsMapper;
import com.chenyue.cm.common.dao.JdSearchHistoryMapper;
import com.chenyue.cm.common.domain.JdHotKeyWords;
import com.chenyue.cm.common.domain.JdSearchHistory;
import com.chenyue.cm.common.service.JdSearchHistoryService;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.live.vo.LiveStudio;
import com.chenyue.cm.match.dao.FormatLiveRecordMapper;
import com.chenyue.cm.match.domain.FormatLiveRecord;
import com.chenyue.cm.match.vo.Address;
import com.chenyue.cm.news.dao.JdNewsMapper;
import com.chenyue.cm.news.domain.JdNews;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author chenyue-cm
 */
@Service(value = "JdSearchHistoryService")
public class JdSearchHistoryServiceImpl extends BaseServiceImpl<JdSearchHistory> implements JdSearchHistoryService {

    private final JdSearchHistoryMapper jdSearchHistoryMapper;

    private final JdNewsMapper jdNewsMapper;

    private final FormatLiveRecordMapper liveRecordMapper;

    private final JdHotKeyWordsMapper hotKeyWordsMapper;

    public JdSearchHistoryServiceImpl(
            @Qualifier("jdSearchHistoryMapper") JdSearchHistoryMapper jdSearchHistoryMapper,
            @Qualifier("jdNewsMapper") JdNewsMapper jdNewsMapper,
            @Qualifier("formatLiveRecordMapper") FormatLiveRecordMapper liveRecordMapper,
            @Qualifier("jdHotKeyWordsMapper") JdHotKeyWordsMapper hotKeyWordsMapper
    ) {
        this.jdSearchHistoryMapper = jdSearchHistoryMapper;
        this.jdNewsMapper = jdNewsMapper;
        this.liveRecordMapper = liveRecordMapper;
        this.hotKeyWordsMapper = hotKeyWordsMapper;
    }

    @Override
    @Resource(name = "jdSearchHistoryMapper")
    public void setBaseMapper(LcBaseMapper<JdSearchHistory, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public List<JdSearchHistory> getSearch(Integer type, Integer userId) {
        LambdaQueryWrapper<JdSearchHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdSearchHistory::getType, type)
                .eq(JdSearchHistory::getUserId, userId)
                .groupBy(JdSearchHistory::getContent)
                .orderByDesc(JdSearchHistory::getCt);
        return jdSearchHistoryMapper.selectList(wrapper);
    }

    @Override
    public Page<List<LiveStudio>> liveSelect(String keyWords, Integer page, Integer rows, Integer userId, Address address) {
        LambdaQueryWrapper<FormatLiveRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(FormatLiveRecord::getTitle, keyWords);
        final String city = address.getCity();
        final String province = address.getProvince();
        if (null != city) {
            wrapper.apply("(isnull(province_code) || city_code = " + city + " || (isnull(city_code) && province_code = " + province + "))");
        }
        Integer total = liveRecordMapper.selectCount(wrapper);
        Page<List<LiveStudio>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        List<FormatLiveRecord> records = liveRecordMapper.selectList(wrapper);
        List<LiveStudio> list = new ArrayList<>();
        for (FormatLiveRecord record : records) {
            LiveStudio studio = new LiveStudio();
            studio.setRecordId(record.getId());
            studio.setLiveId(record.getLiveId());
            studio.setTitle(record.getTitle());
            studio.setLiveLogo(record.getLiveLogo());
            studio.setUserName(record.getUserName());
            studio.setUserImg(record.getHeadImg());
            studio.setParentUserName(record.getThirdName());
            studio.setType(record.getType());
            if (record.getEndTime() != null) {
                //有结束时间 = 看回放
                studio.setLiveState(3);
            } else {
                if (record.getStartTime() == null) {
                    //没开始时间 = 预告
                    studio.setLiveState(2);
                } else {
                    //有开始时间没结束时间 = 直播中
                    studio.setLiveState(1);
                }
            }
            studio.setFormatStartTime(record.getMatchStartTime());
            studio.setVideoUrl(record.getVideoUrl());
            studio.setMatchId(record.getMatchId());
            list.add(studio);
        }
        result.setContent(list);
        //添加搜索历史记录
        JdSearchHistory history = new JdSearchHistory();
        history.setContent(keyWords);
        history.setCt(DateUtils.getToday());
        history.setType(1);
        history.setUserId(userId);
        jdSearchHistoryMapper.insert(history);
        return result;
    }

    @Override
    public Page<List<JdNews>> newsSelect(String keyWords, Integer page, Integer rows, Integer userId) {
        LambdaQueryWrapper<JdNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(JdNews::getTitle, keyWords);
        //添加搜索历史记录
        JdSearchHistory history = new JdSearchHistory();
        history.setContent(keyWords);
        history.setCt(DateUtils.getToday());
        history.setType(2);
        history.setUserId(userId);
        jdSearchHistoryMapper.insert(history);

        Integer total = jdNewsMapper.selectCount(wrapper);
        Page<List<JdNews>> result = new Page<>(page, rows, total);
        wrapper.last(result.convertPage());
        List<JdNews> jdNews = jdNewsMapper.selectList(wrapper);
        result.setContent(jdNews);
        return result;
    }

    @Override
    public List<String> getHotNews() {
        List<String> result = new ArrayList<>();
        LambdaQueryWrapper<JdNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdNews::getIsRecommend, 1)
                .eq(JdNews::getIsShow, 1);
        List<JdNews> jdNews = jdNewsMapper.selectList(wrapper);
        for (JdNews jdNew : jdNews) {
            result.add(jdNew.getTitle());
        }
        return result;
    }

    /**
     * 清空搜索记录
     *
     * @param id 用户id
     */
    @Override
    public void deleteByUserId(Integer id) {
        jdSearchHistoryMapper.delete(
                new LambdaQueryWrapper<JdSearchHistory>()
                        .eq(JdSearchHistory::getUserId, id)
        );
    }

    @Override
    public List<String> getHotKeywords() {
        return hotKeyWordsMapper.selectList(
                new LambdaQueryWrapper<JdHotKeyWords>()
                        .eq(JdHotKeyWords::getIsShow, 1)
                        .orderByAsc(JdHotKeyWords::getOrderNo)
        ).stream().map(JdHotKeyWords::getName).collect(Collectors.toList());
    }
}
